<template>
  <el-dialog
    top="30px"
    width="800px"
    title="项目立项"
    append-to-body
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <div v-loading="loading">
      <table class="table table-borderless table-sm">
        <tr>
          <td width="16%" class="text-muted">项目名称：</td>
          <td width="34%">{{ relatedData.customer_name }}</td>
          <td width="16%" class="text-muted">项目地址：</td>
          <td width="34%">{{ relatedData.address }}</td>
        </tr>
        <tr>
          <td class="text-muted">负责人：</td>
          <td>{{ relatedData.corp_name || '-' }}</td>
          <td class="text-muted">联系电话：</td>
          <td>{{ relatedData.mobile_no }}</td>
        </tr>
        <tr>
          <td class="text-muted">A角:</td>
          <td>{{ relatedData.res_a_name || '-' }}</td>
          <td class="text-muted">B角:</td>
          <td>{{ relatedData.res_b_name || '-' }}</td>
        </tr>
        <tr>
          <td class="text-muted">
            <span class="text-danger">*</span>
            申请金额：
          </td>
          <td>
            <span v-if="viewMode">{{ relatedData.apply_funds || '-' }} 万元</span>
            <el-input
              v-else
              v-model="editData.apply_funds"
              class="pr-4"
              v-input-number="{ min: 0, fixed: 2 }"
              placeholder="申请金额"
            >
              <span slot="append">万元</span>
            </el-input>
          </td>
          <td class="text-muted">申请年限：</td>
          <td>{{ relatedData.load_years || '-' }} 年</td>
        </tr>
        <tr>
          <td class="text-muted">
            <span class="text-danger">*</span>
            贷款用途：
          </td>
          <td colspan="3">
            <span v-if="viewMode">{{ relatedData.funds_use_dir || '-' }}</span>
            <el-input
              v-else
              v-model="editData.funds_use_dir"
              class="form-control-ml"
              placeholder="贷款用途"
            ></el-input>
          </td>
        </tr>
        <template v-if="viewMode || relatedData.bank_id">
          <tr>
            <td class="text-muted">银行：</td>
            <td colspan="3">{{ relatedData.bank_name || '-' }}</td>
          </tr>
        </template>
        <template v-else-if="+relatedData.gua_type === 2 || +relatedData.gua_type === 4">
          <td class="align-middle text-muted">
            <span class="text-danger">*</span>
            选择银行：
          </td>
          <td colspan="3">
            <select-banks
              v-model="editData.bank_id"
              @change="setBankName"
              class="form-control-ml"
            ></select-banks>
          </td>
        </template>
        <template v-else>
          <tr>
            <td class="align-middle text-muted">是否指定银行：</td>
            <td colspan="3">
              <div class="d-flex align-items-center my-2">
                <el-switch
                  v-model="isBank"
                  v-if="!viewMode"
                  active-color="#67C23A"
                  inactive-color="#F56C6C"
                  active-value="1"
                  :active-text="+isBank === 1 ? '是' : '否'"
                  inactive-value="0"
                ></el-switch>
                <span v-else>{{ +isBank === 1 ? '是' : '否' }}</span>
              </div>
            </td>
          </tr>
          <tr v-if="+isBank === 1">
            <td class="align-middle text-muted">选择银行：</td>
            <td colspan="3">
              <select-banks
                v-model="editData.public_bank_ids"
                @change="setPublicName"
                v-if="!viewMode"
                class="form-control-ml"
              ></select-banks>
              <span v-else>{{ relatedData.public_bank_names }}</span>
            </td>
          </tr>
        </template>
        <tr v-if="isUnionType">
          <td class="align-middle text-muted">银行分险比例：</td>
          <td colspan="3" class="align-middle">
            <span v-if="viewMode">{{ letter.bear_rate_divide || '-' }}%</span>
            <el-input
              v-else
              v-input-number="inputOptions"
              v-model="letter.bear_rate_divide"
              class="form-control-ml"
            >
              <span slot="append">%</span>
            </el-input>
          </td>
        </tr>
        <tr v-if="isUnionType">
          <td class="align-middle text-muted">联担分险比例：</td>
          <td colspan="3" class="align-middle">
            <span v-if="viewMode">{{ letter.bear_rate || '-' }}%</span>
            <el-input
              v-else
              v-input-number="inputOptions"
              v-model="letter.bear_rate"
              class="form-control-ml"
            >
              <span slot="append">%</span>
            </el-input>
          </td>
        </tr>
        <tr v-if="isUnionType">
          <td class="text-muted">保费分配比例：</td>
          <td colspan="3">
            <span v-if="viewMode">{{ letter.gua_fee_rate || '-' }}%</span>
            <el-input
              v-else
              v-input-number="inputOptions"
              v-model="letter.gua_fee_rate"
              class="form-control-ml"
            >
              <span slot="append">%</span>
            </el-input>
          </td>
        </tr>
        <tr>
          <td class="text-muted">公司/个人简介：</td>
          <td colspan="3">
            <div v-if="viewMode">{{ relatedData.item_project_des || '-' }}</div>
            <el-input
              v-else
              v-model="editData.item_project_des"
              class="form-control-ml"
              rows="5"
              placeholder="输入公司/个人简介"
              type="textarea"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td class="text-muted">还款计划：</td>
          <td colspan="3">
            <div v-if="viewMode">{{ relatedData.item_return_plan || '-' }}</div>
            <el-input
              v-else
              v-model="editData.item_return_plan"
              class="form-control-ml"
              rows="5"
              placeholder="输入还款计划"
              type="textarea"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td class="text-muted">反担保措施：</td>
          <td colspan="3">
            <div v-if="viewMode">{{ relatedData.item_counter_guarantee || '-' }}</div>
            <el-input
              v-else
              v-model="editData.item_counter_guarantee"
              class="form-control-ml"
              rows="5"
              placeholder="输入反担保措施"
              type="textarea"
            ></el-input>
          </td>
        </tr>
      </table>
      <div class="text-center mt-2" v-if="!viewMode">
        <el-button @click="submit" type="primary" :loading="submitLoading" class="btn-long">
          同意立项
        </el-button>
        <el-button @click="handleVisible" v-if="dismiss" class="btn-long">拒绝</el-button>
      </div>
    </div>

    <project-approve-refuse
      :visible.sync="desVisible"
      @success="handleClose"
      :queryId="queryId"
    ></project-approve-refuse>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import SelectBanks from '@/credit/components/select/SelectOrgBank'
import ProjectApproveRefuse from '@/credit/views/city/program/ProjectApproveRefuse'
export default {
  components: {
    SelectBanks,
    ProjectApproveRefuse,
  },
  props: {
    visible: Boolean,
    relatedData: {
      type: Object,
      default() {
        return {}
      },
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
    dismiss: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      loading: false,
      public_bank_names: '',
      submitLoading: false,
      desVisible: false,
      editData: {},
      letter: {},
      isBank: '0',
      inputOptions: {
        min: 0,
        max: 100,
        fixed: 2,
        onMin: () => this.$message.error('不能小于0'),
        onMax: () => this.$message.error('不能超过100'),
        onFixed: () => this.$message.error('小数点不能超过2位数'),
      },
    }
  },
  computed: {
    ...mapGetters(['org', 'user', 'userId']),
    rejectName() {
      return this.org.orgName + '-' + this.user.realName
    },
    queryId() {
      return this.relatedData.customer_related_id
    },
    guaType() {
      return +this.relatedData.gua_type
    },
    isUnionProvinceType() {
      return this.guaType === 4
    },
    isUnionType() {
      return [1, 4].includes(this.guaType)
    },
  },
  watch: {
    relatedData: {
      handler: function () {
        this.editData = { ...this.relatedData }
        this.public_bank_names = this.relatedData.public_bank_names || ''
        this.isBank = this.relatedData.public_bank_ids ? '1' : '0'
        if (this.isUnionType) {
          this.getLetter()
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {},
  created() {},
  methods: {
    setPublicName(val, name) {
      const bankName = (name && name.length && name[name.length - 1]) || ''
      this.public_bank_names = bankName
    },
    setBankName(val, name) {
      const bankName = (name && name.length && name[name.length - 1]) || ''
      this.editData.bank_name = bankName
    },
    handleClose() {
      this.beforeClose()
      this.$emit('success', true)
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    getLetter() {
      if (!this.relatedData.customer_related_id) {
        return
      }
      const params = {
        'customer_related_id.eq': this.relatedData.customer_related_id,
        'ele_letter_type.eq': 2,
      }
      this.loading = true
      this.$api
        .getData(this.$serviceName, 'ele_letter_info', params)
        .then(res => {
          this.letter = (res && res.data && res.data[0]) || {}
        })
        .finally(() => {
          this.loading = false
        })
    },
    validtor() {
      if (!this.letter.bear_rate_divide) {
        this.$message.warning('银行分险比例')
        return false
      }
      if (!this.letter.bear_rate) {
        this.$message.warning('联担分险比例')
        return false
      }
      if (!this.letter.gua_fee_rate) {
        this.$message.warning('保费分配比例')
        return false
      }
      return true
    },
    submitLetter() {
      const data = {
        customer_related_id: this.relatedData.customer_related_id,
        ele_letter_type: '2',
        submit_person_name: this.org.orgName,
        letter_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd'),
        bear_rate_divide: this.letter.bear_rate_divide,
        bear_rate: this.letter.bear_rate,
        gua_fee_rate: this.letter.gua_fee_rate,
      }
      if (this.letter.ele_letter_info_id) {
        this.$api.updateData(
          this.$serviceName,
          'ele_letter_info',
          this.letter.ele_letter_info_id,
          data
        )
      } else {
        this.$api.addData(this.$serviceName, 'ele_letter_info', data).catch(() => {
          this.$message.error(this.isUnionProvinceType ? '项目立项失败' : '生成联保函失败')
        })
      }
    },
    submit() {
      if (!this.editData.apply_funds) {
        return this.$message.warning('请输入申请金额')
      }
      if (!this.editData.bank_id && +this.relatedData.gua_type === 2) {
        return this.$message.warning('请选择合作银行')
      }
      if (!this.editData.funds_use_dir) {
        return this.$message.warning('请输入贷款用途')
      }

      const bankId = (this.isBank && this.editData.public_bank_ids) || null
      const dateNow = this.$utils.dateFormat(new Date())
      const data = {
        item_person: this.userId,
        item_project_des: this.editData.item_project_des,
        item_counter_guarantee: this.editData.item_counter_guarantee,
        item_return_plan: this.editData.item_return_plan,
        item_date: dateNow,
        public_bank_ids: bankId,
        public_bank_names: this.public_bank_names,
        item_status: 1, // 状态
        item_confuse_des: '',
        apply_funds: this.editData.apply_funds,
        funds_use_dir: this.editData.funds_use_dir,
        bank_id: this.editData.bank_id || '',
        bank_name: this.editData.bank_name || '',
      }

      // 区县农担立项，省农担自动 联保受理 通过
      if (this.isUnionProvinceType) {
        data.is_approval_gua_date = dateNow
        data.is_approval_gua = '1'
      }
      this.submitLoading = true
      this.$api
        .updateData(
          this.$serviceName,
          'customer_related',
          this.relatedData.customer_related_id,
          data
        )
        .then(() => {
          this.$emit('success', true)
          this.$message.success('立项成功')
          if (this.isUnionType) {
            if (!this.validtor()) {
              return
            }
            this.submitLetter()
          }
          this.beforeClose()
        })
        .catch(() => {
          this.$message.error('项目立项失败')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    handleVisible() {
      this.desVisible = true
    },
  },
}
</script>
<style lang="scss" scoped></style>
